<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/10/15
 * Time: 17:45
 */

namespace app\common\command;


use think\console\Command;
use think\console\Input;
use think\console\Input\Option;
use think\console\Input\Argument;
use think\console\Output;
use think\Exception;

class Curd extends Command
{
    protected $base_path;
    protected $module;
    protected $controller;

    protected function configure()
    {
        $this->setName('curd')
            ->addArgument('name', Argument::OPTIONAL, "模块名称和控制器名称 eg:admin/test")
            ->addOption('father_class', null, Option::VALUE_OPTIONAL, '控制器继承类，默认Admin')
            ->addOption('view_father_class', null, Option::VALUE_OPTIONAL, '视图控制器继承类? , 默认Admin')
            ->addOption('service', null, Option::VALUE_OPTIONAL, '是否需要服务层? , value:1 or 0')
            ->addOption('view', null, Option::VALUE_OPTIONAL, '是否需要视图? , value:1 or 0')
            ->addOption('model_path', null, Option::VALUE_OPTIONAL, 'model存放目录, eg:admin or common or other')
            ->addOption('base_path', null, Option::VALUE_OPTIONAL, '基础目录，起始目录为根目录，不要/结尾')
            ->addOption('list', null, Option::VALUE_OPTIONAL, '管理后台的列表名称，不生成不要填写')
            ->addOption('list_options', null, Option::VALUE_OPTIONAL, '生成列表配置项，只加载配置列。格式:title-标题-ON/OFF-100,desc-描述，字段-列标题-是否开关（是开关输入开关标题,格式：/）-最小列宽')
            ->addOption('form', null, Option::VALUE_OPTIONAL, '管理后台的表单名称，不生成不要填写')
            ->addOption('form_options', null, Option::VALUE_OPTIONAL, '生成表单填写配置项，只加载配置项，格式：格式：name-text-姓名-require,desc-textarea-描述  ' .
                '用英文逗号分隔，require选填。支持类型：text,num,textarea,checkbox,select,data(日期),datetime(日期时间),time(时间),rich（富文本编辑器,暂不支持）')
            //支持表单格式：text\checkbox\select\number\date\datetime\textarea\upload
            ->setDescription('curd一键生成 请先创建好对应数据表 目前仅完整支持模块内控制器生成');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
        if (!$name) {
            $output->writeln('请输入名称');
            return false;
        }
        $name = explode('/', $name);
        if (count($name) != 2) {
            $output->writeln('请输入正确的名称');
            return false;
        }
        $service = $input->getOption('service');//是否包含视图
        $service = isset($service) ? $service : true;
        $view = $input->getOption('view');//是否包含视图
        $view = isset($view) ? $view : true;
        $this->base_path = $input->getOption('base_path');
        if ($this->base_path) {
            $this->base_path = BASE_ROOT . $this->base_path . '/';
            if (!is_dir($this->base_path)) {
                $output->writeln('基础目录不存在');
                mkdir($this->base_path);
                $output->writeln('基础目录创建完成');
            }
        } else {
            $this->base_path = APP_PATH;
        }
        //继承类进行判断
        $father_class = $input->getOption('father_class');
        $father_class = isset($father_class) ? $father_class : 'Admin';
        $view_father_class = $input->getOption('view_father_class');
        $view_father_class = isset($view_father_class) ? $view_father_class : 'Admin';
        //TODO 增加是否为插件选项 生成插件配置文件
        $model_path = $input->getOption('model_path');
        $this->module = $name[0];
        $this->controller = ucwords($name[1]);
        $model_path = $model_path ? $this->base_path . $model_path : $this->base_path . $this->module;
        $model_path = $model_path . '/model/';
        $path = $this->base_path . $this->module;
        $output->writeln('执行中：' . $this->controller);
        if (!is_dir($path)) {
            $output->writeln('模块目录不存在');
            mkdir($path);
            $output->writeln('模块目录创建完成');
        }
        if (!is_dir($path . '/controller')) {
            $output->writeln('控制器目录不存在');
            mkdir($path . '/controller');
            $output->writeln('控制器目录创建完成');
        }
        if ($service && !is_dir($path . '/service')) {
            $output->writeln('服务层目录不存在');
            mkdir($path . '/service');
            $output->writeln('服务层目录创建完成');
        }
        if ($service && !is_dir($path . '/facade')) {
            $output->writeln('facade目录不存在');
            mkdir($path . '/facade');
            $output->writeln('facade目录创建完成');
        }
        if ($view && !is_dir($path . '/controller/view')) {
            $output->writeln('视图层目录不存在');
            mkdir($path . '/controller/view');
            $output->writeln('视图层目录创建完成');
        }
        if (!is_dir($model_path)) {
            $output->writeln('model层目录不存在');
            mkdir($model_path);
            $output->writeln('model层目录创建完成');
        }
        $date = date('Y/m/d', time());
        $time = date('m:d', time());
        $file_path = $path . '/controller/' . $this->controller . 'Controller.php';
        //TODO 增加选项判断是否有toggle
        if (!is_file($file_path)) {
            $output->writeln('正在创建控制器文件');
            $has_service_use = "";
            $has_service_index = "";
            if ($service) {
                $has_service_use = "use app\\{$this->module}\\facade\\{$this->controller};";
                $has_service_index = "\$res = {$this->controller}::getList(\$page,\$limit,\$keyword);" . PHP_EOL . "        return \$this->results(\$res);";
            }
            $file_content = <<<EOT
<?php
/**
 * Created by INGEPHP CURD.
 * User: 
 * Date: $date
 * Time: $time
 */

namespace app\\$this->module\\controller;
use app\common\controller\\$father_class;
use think\\facade\\Request;
$has_service_use

class {$this->controller}Controller extends $father_class
{
    
    /**
     * 列表方法
     * @method get
     * @param int \$page 页码
     * @param int \$limit 每页数量
     * @param string \$keyword 关键词
     * @return json
     */
    public function index()
    {
        \$page = Request::param('page','1','intval');
        \$limit = Request::param('limit','15','intval');
        \$keyword = Request::param('keyword','');
        {$has_service_index}
    }

    /**
     * 表单提交保存操作
     * @method post
     * @param
     * @return json
     */
    public function save()
    {
        \$data = Request::param();
        //数据验证
        return \$this->results({$this->controller}::save(\$data));
    }
    /**
     * 表单提交更新
     * @method post
     * @param int \$id 需要更新数据的id
     * @param array  post提交更新的内容
     * @return json
     */
    public function update(\$id)
    {
        if(!intval(\$id)){
            \$this->results(['code' => 4001, 'msg' => '参数错误', 'data' => '']);
        }
        \$data = Request::except('id','post');
        //数据验证
        
        return \$this->results({$this->controller}::update(\$id,\$data));
    }
    /**
     * 表单删除
     * @method get
     * @param int \$id 需要删除数据的id
     * @return json
     */
    public function delete(\$id)
    {
        if(!intval(\$id)){
            \$this->results(['code' => 4001, 'msg' => '参数错误', 'data' => '']);
        }
        return \$this->results({$this->controller}::delete(\$id));
    }
    /**
     * 根据ID获取单个数据
     * @method get
     * @param int \$id 获取的id
     * @return json
     */
    public function read(\$id)
    {
        return \$this->results({$this->controller}::getById(\$id));
    }
}
EOT;
            $file = fopen($file_path, "w");
            fwrite($file, $file_content);
            fclose($file);
            $output->writeln('控制器文件创建完成：' . $file_path);
        } else {
            $output->writeln('控制器文件已存在：' . $file_path);
        }
        $file_path = $model_path . $this->controller . 'Model.php';
        if (!is_file($file_path)) {
            $output->writeln('正在创建model文件');
            $file_content = <<<EOT
<?php
/**
 * Created by INGEPHP CURD.
 * User: 
 * Date: $date
 * Time: $time
 */

namespace app\\$this->module\\model;


use think\Model;
use think\model\concern\SoftDelete;

class {$this->controller}Model extends Model
{
    use SoftDelete;
    protected \$deleteTime = 'delete_time';
}
EOT;
            $file = fopen($file_path, "w");
            fwrite($file, $file_content);
            fclose($file);
            $output->writeln('model文件创建完成：' . $file_path);
        } else {
            $output->writeln('model文件已存在：' . $file_path);
        }
        if ($view) {
            $file_path = $path . '/controller/view/' . $this->controller . 'Controller.php';
            if (!is_file($file_path)) {
                $output->writeln('正在创建视图控制器文件');
                $file_content = <<<EOT
<?php
/**
 * Created by INGEPHP CURD.
 * User: 
 * Date: $date
 * Time: $time
 */

namespace app\\$this->module\\controller\\view;

use app\common\controller\\$view_father_class;
use think\\facade\\Request;

class {$this->controller}Controller extends $view_father_class
{
    /**
     * 列表视图显示
     * @method get
     * @param
     * @return
     */
    public function index(){
        return \$this->fetch();
    }
    /**
     * 新增数据视图显示
     * @method get
     * @param
     * @return
     */
    public function add(){
        return \$this->fetch();
    }
    /**
     * 编辑数据视图显示
     * @method get
     * @param \$id int 需要更新数据的id
     * @return
     */
    public function edit(\$id){
        if(!intval(\$id)){
            \$this->error('参数错误');
        }
        \$this->assign('id',\$id);
        return \$this->fetch();
    }
}
EOT;
                $file = fopen($file_path, "w");
                fwrite($file, $file_content);
                fclose($file);
                $output->writeln('视图控制器文件创建完成：' . $file_path);
            } else {
                $output->writeln('视图控制器文件已存在：' . $file_path);
            }
            $this->createListHtml($input, $output);
            $this->createFormHtml($input, $output);
        }

        if ($service) {
            //facade
            $file_path = $path . '/facade/' . $this->controller . '.php';
            if (!is_file($file_path)) {
                $output->writeln('正在创建facade文件');
                $file_content = <<<EOT
<?php
/**
 * Created by INGEPHP CURD.
 * User: 
 * Date: $date
 * Time: $time
 */

namespace app\\$this->module\\facade;


use think\Facade;

class $this->controller extends Facade
{
    public static function getFacadeClass()
    {
        return 'app\\{$this->module}\\service\\{$this->controller}Service';
    }
}
EOT;
                $file = fopen($file_path, "w");
                fwrite($file, $file_content);
                fclose($file);
                $output->writeln('facade文件创建完成：' . $file_path);
            } else {
                $output->writeln('facade文件已存在：' . $file_path);
            }
            //service
            $file_path = $path . '/service/' . $this->controller . 'Service.php';
            if (!is_file($file_path)) {
                $output->writeln('正在创建服务层文件');
                $file_content = <<<EOT
<?php
/**
 * Created by INGEPHP CURD.
 * User: 
 * Date: $date
 * Time: $time
 */

namespace app\\$this->module\\service;


use app\\$this->module\\model\\{$this->controller}Model;

class {$this->controller}Service
{
    /**
     * 获取列表
     * @param int \$page 分页
     * @param int \$limit 每页数量
     * @param string \$keyword 搜索关键词
     * @return json
     */
    public function getList(\$page = 1, \$limit = 15, \$keyword = "")
    {
        if (!empty(\$keyword)) {
            \$map[] = ['name', 'like', '%' . \$keyword . '%'];
            \$list = {$this->controller}Model::where(\$map);
        } else {
            \$list = new {$this->controller}Model;
        }
        \$total = clone \$list;
        \$list = \$list->page(\$page, \$limit)->select();
        \$total = \$total->count();
        return ['code' => 1001, 'msg' => '获取成功', 'data' => \$list, 'total' => \$total];
    }

    /**
     * 新增数据
     * @param array 传入的数据
     * @return json
     */
    public function save(\$data)
    {
        $$this->controller = new {$this->controller}Model;
        \$res = $$this->controller->save(\$data);
        if (\$res) {
            return ['code' => 1001, 'msg' => '新增成功', 'data' => \$res];
        }
        return ['code' => 4001, 'msg' => '新增失败', 'data' => ''];
    }
    /**
     * 根据ID更新数据
     * @param int \$id 需要更新的数据ID
     * @param array 传入的数据
     * @return json
     */
    public function update(\$id, \$data)
    {
        $$this->controller = new {$this->controller}Model;
        \$res = $$this->controller->save(\$data, ['id'=> \$id]);
        if (\$res) {
            return ['code' => 1001, 'msg' => '更新成功', 'data' => \$res];
        }
        return ['code' => 4001, 'msg' => '更新失败', 'data' => ''];
    }
    /**
     * 根据ID删除数据
     * @param int \$id 需要更新的数据ID
     * @return json
     */
    public function delete(\$id)
    {
        \$res = {$this->controller}Model::destroy(\$id);
        if (\$res) {
            return ['code' => 1001, 'msg' => '删除成功', 'data' => \$res];
        }
        return ['code' => 4001, 'msg' => '删除失败', 'data' => ''];
    }
    /**
     * 根据ID获取数据
     * @param int 
     * @return json
     */
    public function getById(\$id)
    {
        $$this->controller = new {$this->controller}Model;
        \$res      = $$this->controller::where('id', \$id)->find();
        if (\$res) {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => \$res];
        }
        return ['code' => 4001, 'msg' => '数据不存在', 'data' => ''];
    }
}
EOT;
                $file = fopen($file_path, "w");
                fwrite($file, $file_content);
                fclose($file);
                $output->writeln('服务层文件创建完成：' . $file_path);
            } else {
                $output->writeln('服务层文件已存在：' . $file_path);
            }

        }
        $output->writeln('success');

    }

    protected function getHtmlPath($output)
    {
        $path = BASE_ROOT . 'public/theme/' . strtolower($this->module) . '/' . lcfirst($this->controller);
        if (!is_dir($path)) {
            $output->writeln('模板目录不存在：' . $path);
            mkdir($path, 0777, true);
            $output->writeln('模板目录创建完成：' . $path);
        }
        return $path;
    }

    /**
     * 创建路由
     * User: Thans
     * Date: 2018/10/17
     * Time: 11:02
     * @param
     * @return
     */
    //TODO 自动创建对应路由
    protected function createRoute()
    {

    }

    protected function createFormHtml($input, $output)
    {
        //命令行格式：
        $tips = '格式：name-text-姓名-require,desc-textarea-描述  ' .
            '用英文逗号分隔，require选填。支持类型：text,num,textarea,checkbox,select,data(日期),datetime(日期时间),time(时间),rich（富文本编辑器,暂不支持）';
        $form = $input->getOption('form');
        if (!$form) {
            $output->writeln('表单不生成');
            return false;
        }
        $options = $input->getOption('form_options');
        if (!$options) {
            $output->writeln('表单生成缺少配置项');
            return false;
        }
        $controller = lcfirst($this->controller);//url生成需要
        //TODO 判断是否为插件，调整插件目录
        //创建新增、编辑表单html
        $path = $this->getHtmlPath($output);
        $file = $path . '/form.html';
        $output->writeln('正在创建表单模板：' . $file);
        $time_js = '';
        $html = "<div class=\"layui-form\" lwid100 iwid300 lay-filter=\"form\">\n";
        //解析规则
        try {
            $options = explode(',', $options);
            foreach ($options as $var) {
                $arr = explode('-', $var);
                $arr[3] = isset($arr[3]) ? $arr[3] : '';
                switch ($arr[1]) {
                    case 'text':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="text" lay-verify="$arr[3]" $arr[3] name="$arr[0]" value="" autocomplete="off"
                       class="layui-input">
        </div>
    </div>
EOT;
                        break;
                    case 'num':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="number" lay-verify="$arr[3]" name="$arr[0]" value="" autocomplete="off"
                       class="layui-input">
        </div>
    </div>
EOT;
                        break;
                    case 'textarea':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <textarea placeholder="" name="$arr[0]" lay-verify="$arr[3]" class="layui-textarea"></textarea>
        </div>
    </div>
EOT;
                        break;
                    case 'checkbox':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="checkbox" checked="" value="1" lay-verify="$arr[3]" name="$arr[0]" lay-skin="switch" lay-text="ON|OFF">
        </div>
    </div>
EOT;
                        break;
                    case 'select':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <select name="$arr[0]" lay-verify="$arr[3]">
            </select>
        </div>
    </div>
EOT;
                        break;
                    case 'data':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input" id="$arr[0]"  lay-verify="$arr[3]" placeholder="yyyy-MM-dd" name="$arr[0]" >
        </div>
    </div>
EOT;
                        $time_js .= "laydate.render({
    elem: '#$arr[0]'
  });";
                        break;
                    case 'datatime':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input" id="$arr[0]"  lay-verify="$arr[3]" placeholder="yyyy-MM-dd HH:mm:ss" name="$arr[0]" >
        </div>
    </div>
EOT;
                        $time_js .= "laydate.render({
    elem: '#$arr[0]'
    ,type: 'datetime'
  });";
                        break;
                    case 'time':
                        $html .= <<<EOT
    <div class="layui-form-item">
        <label class="layui-form-label">$arr[2]</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input" id="$arr[0]"  lay-verify="$arr[3]" placeholder="HH:mm:ss" name="$arr[0]" >
        </div>
    </div>
EOT;
                        $time_js .= "laydate.render({
    elem: '#$arr[0]'
    ,type: 'time'
  });";
                        break;
                }
                $html .= "\n";
            }
        } catch (Exception $e) {
            $output->writeln('表单配置项解析错误。' . $tips);
            return false;
        }
        $html .= <<<EOT
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="form">保存</button>
        </div>
    </div>
</div>
EOT;
        $time_m = '';
        if ($time_js) {
            $time_m = ",'laydate'";
        }
        $time_js = "var laydate = layui.laydate;\n" . $time_js;

        $file_handle = fopen($file, "w");
        fwrite($file_handle, $html);
        fclose($file_handle);
        $output->writeln('创建表单模板完成：' . $file);
        $file = $path . '/add.html';
        $html = <<<EOT
{extend name="../admin/common/base" /}
{block name="body"}
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-body">
                            {include file="$controller/form" /}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}
{block name="my_js"}
<script>
    layui.use(['element', 'admin', 'form'$time_m], function () {
        var element = layui.element
            , admin = layui.admin
            , $ = layui.$
            , form = layui.form;
        $time_js
        //form.verify({});
        form.on('submit(form)', function (data) {
            admin.ajax('{:url('{$this->module}/{$controller}/save')}', data.field, function (data) {
                if (data.code == 1001) {
                    if($('#layui-icon-refresh',parent.document)){
                        $('#layui-icon-refresh',parent.document).click();
                    }
                    layer.confirm(data.msg + ',是否继续添加?', {
                        icon: 3,
                        title: '提示',
                        btn: ['继续', '返回']
                    }, function (index) {
                        location.reload();
                    }, function () {
                        admin.closeSelf()
                    });
                } else {
                    layer.msg(data.msg);
                }
            });
        });
    });
</script>
{/block}
EOT;
        $file_handle = fopen($file, "w");
        fwrite($file_handle, $html);
        fclose($file_handle);
        $output->writeln('正在创建新增表单模板：' . $file);
        //创建对应编辑表单
        $output->writeln('创建表单新增表单完成：' . $file);
        $file = $path . '/edit.html';
        $output->writeln('正在创建编辑表单模板：' . $file);
        //创建对应编辑表单
        $html = <<<EOT
{extend name="../admin/common/base" /}
{block name="body"}
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-body">
                            {include file="$controller/form" /}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}
{block name="my_js"}
<script>
    layui.use(['element', 'admin', 'form'$time_m], function () {
        var element = layui.element
            , admin = layui.admin
            , $ = layui.$
            , form = layui.form;
        $time_js
        var id = '{\$id}';
        admin.ajax('{:url('{$this->module}/{$controller}/read',array('id'=>\$id))}','',function (data) {
            if (data.code == 1001) {
                var value = {};
                $.each(data.data,function(key,val) {
                    value[key] = val
                });
                form.val("form",value)
            } else {
                layer.msg(data.msg + '请联系管理员。');
            }
        },'','get');
        // form.verify({});
        form.on('submit(form)', function (data) {
            admin.ajax('{:url('{$this->module}/{$controller}/update',array('id'=>\$id))}', data.field, function (data) {
                if (data.code == 1001) {
                    if($('#layui-icon-refresh',parent.document)){
                        $('#layui-icon-refresh',parent.document).click();
                    }
                    layer.confirm(data.msg + ',是否继续修改?', {
                        icon: 3,
                        title: '提示',
                        btn: ['继续', '返回']
                    }, function (index) {
                        location.reload();
                    }, function () {
                        admin.closeSelf()
                    });
                } else {
                    layer.msg(data.msg);
                }
            },'','put');
        });
    });
</script>
{/block}
EOT;
        $file_handle = fopen($file, "w");
        fwrite($file_handle, $html);
        fclose($file_handle);
        $output->writeln('创建表单编辑表单完成：' . $file);
    }

    /**
     * 生成后台列表模板
     * @method get
     * User: Thans
     * Date: 2018/10/16
     * Time: 10:48
     * @param
     * @return
     */
    protected function createListHtml($input, $output)
    {
        $controller = lcfirst($this->controller);
        $list = $input->getOption('list');
        if (!$list) {
            $output->writeln('列表不生成');
            return false;
        }
        $options = $input->getOption('list_options');
        if (!$options) {
            $output->writeln('列表生成缺少配置项，格式如下:title-标题-ON/OFF-100,desc-描述，字段-列标题-是否开关（是开关输入开关标题）-最小列宽');
            return false;
        }
        $options = explode(',', $options);
        if (!is_array($options)) {
            $output->writeln('列表配置项错误，格式如下:title-标题-ON/OFF-100,desc-描述，字段-列标题-是否开关（是开关输入开关标题）-最小列宽');
            return false;
        }
        //进行解析

        try {
            $table_json = '';
            $status = '';
            $status_js = '';
            foreach ($options as $val) {
                $arr = explode('-', $val);
                $arr[3] = isset($arr[3]) ? $arr[3] : 100;
                $arr[2] = isset($arr[2]) ? $arr[2] : 0;
                $arr[2] = str_replace('/', '|', $arr[2]);
                if ($arr[2]) {
                    $status_js = "form.on('switch($arr[0])', function (obj) {
        });";
                    $table_json .= ",{field: '$arr[0]', title: '$arr[1]', templet: '#$arr[0]', width: $arr[3]}" . PHP_EOL;
                    $status .= "<script type=\"text/html\"  value=\"{{d.id}}\" id=\"$arr[0]\">
    <input type=\"checkbox\" name=\"$arr[0]\" lay-skin=\"switch\" lay-text=\"$arr[2]\" lay-filter=\"status\" {{
           d.$arr[0]== 1 ? 'checked' : '' }}>
</script>";
                } else {
                    $table_json .= ",{field: '$arr[0]', title: '$arr[1]', minWidth: $arr[3]}" . PHP_EOL;
                }
            }
        } catch (Exception $e) {
            $output->writeln('列表配置项错误，格式如下:title-标题-ON/OFF-100,desc-描述，字段-列标题-是否开关（是开关输入开关标题）-最小列宽');
            return false;
        }
        $path = $this->getHtmlPath($output);
        //创建新增、编辑表单html
        $file_path = $path . '/index.html';
        $output->writeln('正在列表表单模板：' . $file_path);
        $html = <<<EOT
{extend name="../admin/common/base" /}
{block name="body"}
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-header">{$list}列表</div>
                        <div class="layui-card-body admin-table">
                            <div class="layui-row admin-table-action">
                                <div class="layui-col-md6 tool-action">
                                    <a data-href="{:url('{$this->module}/view.{$controller}/add')}"
                                       data-title="新增{$list}"
                                       admin-event="formLayer"
                                       class="layui-btn layui-btn-sm layui-btn-radius layui-btn-primary">
                                        <i class="layui-icon layui-icon-add-circle"></i>
                                    </a>
                                    <button id="layui-icon-refresh"
                                            class="layui-btn layui-btn-sm layui-btn-radius layui-btn-primary">
                                        <i class="layui-icon layui-icon-refresh"></i>
                                    </button>
                                </div>
                                <div class="layui-col-md6 search-form">
                                    <div class="layui-form layui-form-pane search">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">搜索</label>
                                            <div class="layui-input-inline">
                                                <input type="text" name="keyword" lay-verify="required"
                                                       placeholder="请输入" autocomplete="off" class="layui-input">
                                            </div>
                                            <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-primary search-submit">
                                                <i class="layui-icon layui-icon-search"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="list-table" lay-filter="list-table"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}
{block name="my_js"}
<script type="text/html" id="menu">
    <a class="layui-btn layui-btn-xs layui-bg-gray" data-title="{$list}编辑" data-href="{:url('{$this->module}/view.{$controller}/edit','','')}/{{d.id}}.html"
       admin-event="formLayer" >编辑</a>
    <a class="layui-btn layui-btn-xs layui-bg-gray" lay-event="delete">删除</a>
</script>
$status
<script>
    layui.use(['element', 'admin', 'table', 'form'], function () {
        var table = layui.table
            , admin = layui.admin
            , form = layui.form
            , $ = layui.$;
        var list_table = admin.table(table, 'list-table', '{:url('{$this->module}/{$controller}/index')}', {
            page: true
            , cols: [[
                {field: 'id', title: 'ID', width: 50}
                $table_json
                , {fixed: 'right', align: 'center', templet: '#menu', width: 140}
            ]]
        });

        $status_js
        $('#layui-icon-refresh').click(function () {
            list_table.reload();
        });
        admin.enter(function () {
            $('.search-submit').click();
        });
        $('.search-submit').click(function () {
            var keyword = $("input[name='keyword']").val();
            list_table.reload({
                where: {
                    keyword: keyword
                }
            });
        });
        table.on('tool(list-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            if(layEvent === 'delete'){
                layer.confirm('真的删除行么', function (index) {
                    admin.ajax('{:url('{$this->module}/{$controller}/delete','','')}' + '/' + data.id, '', function (data) {
                        if (data.code == 1001) {
                            obj.del();
                            layer.close(index);
                            layer.msg(data.msg);
                        } else {
                            layer.msg(data.msg);
                        }
                    }, '', 'delete');
                });
            }
        });
    });
</script>
{/block}
EOT;
        $file = fopen($file_path, "w");
        fwrite($file, $html);
        fclose($file);
        $output->writeln('创建列表模板完成：' . $file_path);
    }
}